< previous page page_338 next page >

Page 338
9f31265bb40b592b1929e18a47ab28e5.gif
   txtResult = CInt(txtDividend) / CInt(txtDivisor)

   Exit Sub

Error_EH:
      MsgBox "A divide by error has occurred (value / 0) " & _
             "which means that someone input some bad data into the
program."
   Exit Sub
End Sub
Although this is just some sample code that doesnt do a lot, it does demonstrate the common format youll use in any routine in which you need to handle errors. Your first line of executable code should be an On Error Goto <LabelName> statement. This informs Visual Basic that if an error occurs anywhere after the On Error GoTo statement, the program should jump to the label named Error_EH. This label name must be within the same procedure. There is no global error-handling technique in Visual Basic.
If you attempt to divide by a number by zero, the line of code that does the division will cause an error to occur, in which case Visual Basic starts executing the lines of code after the error label. This example displays a message box telling the user that a divide-by error has occurred. Its not very elegant, but it does show you how the error handling works.
Notice the Exit Sub routine right before the Error_EH label. This is there in case no error occurs. If you dont put an Exit Sub before your label, Visual Basic simply drops right into the error-handling label. Labels are not executable code, they are just place markers.
Statements to Put in an Error Label
In the previous examples, after an error occurs, we simply exit the procedure. There are actually four different statements you can use after an error occurs:
Resume Next
Resume [<LabelName>]
Resume
Exit Sub/Exit Function
You will learn about each of these in this chapter.

 
< previous page page_338 next page >

If you like this book, buy it!